package com.example.todolist.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.todolist.dto.business.PlanCountDTO;
import com.example.todolist.dto.business.PlanCreateDTO;
import com.example.todolist.dto.business.PlanStatusCountDTO;
import com.example.todolist.dto.business.QueryPlanByConditionDTO;
import com.example.todolist.mapper.PlanMapper;
import com.example.todolist.mapper.TeamFarMapper;
import com.example.todolist.model.Plan;
import com.example.todolist.model.TeamFarDO;
import com.example.todolist.response.BaseResponse;
import com.example.todolist.response.SystemResponse;
import com.example.todolist.service.PlanService;
import com.example.todolist.service.SysUserService;
import com.example.todolist.util.HttpServletRequestUtil;
import com.example.todolist.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2022-02-26
 */
@Service
public class PlanServiceImpl extends ServiceImpl<PlanMapper, Plan> implements PlanService {

    @Resource
    private PlanMapper planMapper;
    @Resource
    private TeamFarMapper teamFarMapper;
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserSubscribeServiceImpl userSubscribeService;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public BaseResponse planCreate(PlanCreateDTO dto) {
        Plan plan = BeanUtil.copyProperties(dto, Plan.class);
        plan.setUid(getUid());
        String openId  = sysUserService.selectOpenIDByUID(getUid());
        plan.setPlanStartTime(dto.getPlanStartTime().plusHours(8));
        plan.setPlanEndTime(dto.getPlanEndTime().plusHours(8));
        plan.setStatus("未完成");
        boolean save = save(plan);
        if (save) {
            DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String dtime = dtf2.format(dto.getPlanStartTime());
            String result =  userSubscribeService.Auth(openId,dtime,dto.getTitle());
            return SystemResponse.success();
        }
        return SystemResponse.fail("新增规划失败");
    }

    @Override
    public BaseResponse queryPlanByCondition(QueryPlanByConditionDTO dto) {
//        String format = dto.getPlanStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        List<Plan> planList = planMapper.queryPlanByCondition(dto.getPlanStartTime(),dto.getOpenid());
        return SystemResponse.success(planList, planList.size());
    }

    @Override
    public BaseResponse queryPlanGroupByYear(QueryPlanByConditionDTO dto,String openID) {

        ArrayList<PlanCountDTO> planCountDTOS = new ArrayList<>();
        for (int i = 1; i < 6; i++) {
            PlanCountDTO planCountDTO = planMapper.queryPlanGroupByYear(dto.getPlanStartTime(),dto.getOpenid(),Integer.valueOf(i).toString());
            PlanCountDTO teamCountDTO = teamFarMapper.queryPlanGroupByYear(dto.getPlanStartTime(), openID, Integer.valueOf(i).toString());
            if (planCountDTO.getPlanType() == null && teamCountDTO.getPlanType() == null) {
                PlanCountDTO planCount = new PlanCountDTO();
                planCount.setPlanType(Integer.valueOf(i).toString());
                planCount.setNumber("0");
                planCountDTOS.add(planCount);
                continue;
            }else if(planCountDTO.getPlanType() != null && teamCountDTO.getPlanType() == null){
                PlanCountDTO planCount = new PlanCountDTO();
                planCount.setPlanType(Integer.valueOf(i).toString());
                planCount.setNumber(planCountDTO.getNumber());
                planCountDTOS.add(planCount);
                continue;
            }else if(planCountDTO.getPlanType() == null && teamCountDTO.getPlanType() != null){
                PlanCountDTO planCount = new PlanCountDTO();
                planCount.setPlanType(Integer.valueOf(i).toString());
                planCount.setNumber(teamCountDTO.getNumber());
                planCountDTOS.add(planCount);
                continue;
            } else if (planCountDTO.getPlanType() != null && teamCountDTO.getPlanType() != null) {
                PlanCountDTO planCount = new PlanCountDTO();
                planCount.setPlanType(Integer.valueOf(i).toString());
                planCount.setNumber(new BigInteger(planCountDTO.getNumber()).add(new BigInteger(teamCountDTO.getNumber())).toString());
                planCountDTOS.add(planCount);
                continue;
            } else {
                return SystemResponse.fail("计算事项类型统计失败");
            }
        }
        ArrayList<PlanStatusCountDTO> planStatusCountDTOS = new ArrayList<>();
        String status = null;
        String statusTwo = null;
        for (int i = 1; i < 3; i++) {
            if (i == 1) {
                 status = "已完成";
                statusTwo = "1";
            } else {
                 status = "未完成";
                statusTwo = "0";
            }
            PlanStatusCountDTO planStatusCountDTO = planMapper.queryPlanStatusGroupByYear(dto.getPlanStartTime(), dto.getOpenid(),status);
            PlanStatusCountDTO teamCountDTO = teamFarMapper.queryPlanStatusGroupByYear(dto.getPlanStartTime(), openID,statusTwo);
            if (planStatusCountDTO.getStatus() == null && teamCountDTO.getStatus() == null) {
                planStatusCountDTO.setStatus(status);
                planStatusCountDTO.setNumber("0");
                planStatusCountDTOS.add(planStatusCountDTO);
                continue;
            } else if (planStatusCountDTO.getStatus() != null && teamCountDTO.getStatus() == null) {
                planStatusCountDTO.setStatus(status);
                planStatusCountDTO.setNumber(planStatusCountDTO.getNumber());
                planStatusCountDTOS.add(planStatusCountDTO);
                continue;
            } else if (planStatusCountDTO.getStatus() == null && teamCountDTO.getStatus() != null) {
                planStatusCountDTO.setStatus(status);
                planStatusCountDTO.setNumber(teamCountDTO.getNumber());
                planStatusCountDTOS.add(planStatusCountDTO);
                continue;
            } else if (planStatusCountDTO.getStatus() != null && teamCountDTO.getStatus() != null) {
                planStatusCountDTO.setStatus(status);
                planStatusCountDTO.setNumber(new BigInteger(planStatusCountDTO.getNumber()).add(new BigInteger(teamCountDTO.getNumber())).toString());
                planStatusCountDTOS.add(planStatusCountDTO);
                continue;
            } else {
                return SystemResponse.fail("计算事项完成状态统计失败");
            }

        }
        HashMap<Object, Object> map = new HashMap<>();
        map.put("typeList",planCountDTOS);
        map.put("statusList",planStatusCountDTOS);
        return SystemResponse.success(map);
    }


    public BaseResponse queryAllByOpenId() {
        String uid = getUid();
        LambdaQueryWrapper<Plan> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Plan::getUid,uid);
        List<Plan> planList = planMapper.selectList(lambdaQueryWrapper);
        return SystemResponse.success(planList, planList.size());
    }

    @Override
    public BaseResponse queryPlanByUidAndType(Plan plan) {
        QueryWrapper<Plan> planQueryWrapper = new QueryWrapper<>();
        planQueryWrapper.eq("uid",plan.getUid());
        planQueryWrapper.eq("plan_type",plan.getPlanType());
        List<Plan> planList = this.baseMapper.selectList(planQueryWrapper);
        return SystemResponse.success(planList, planList.size());
    }

    @Override
    public BaseResponse queryAllPlanDateByUid(String uid) {
        QueryWrapper<Plan> planQueryWrapper = new QueryWrapper<>();
        planQueryWrapper.eq("uid",uid);
        List<Plan> planList = this.baseMapper.selectList(planQueryWrapper);
        List<LocalDateTime> localDateTimes= planList.stream().map(Plan::getPlanStartTime).collect(Collectors.toList());
        ArrayList<String> newList = new ArrayList<>();
        for (LocalDateTime localDateTime : localDateTimes) {
            String timeStr=localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            newList.add(timeStr);
        }
        List<String> distinct = newList.stream().distinct().collect(Collectors.toList());
        return SystemResponse.success(distinct,distinct.size());
    }

    @Override
    public BaseResponse deletePlanById(String id) {
        int i = this.baseMapper.deleteById(id);
        if (i == 1) {
            return SystemResponse.success();
        } else {
            return SystemResponse.fail();
        }
    }

    @Override
    public BaseResponse queryPlanById(Long id) {
        return SystemResponse.success(getById(id));
    }

    @Override
    public BaseResponse editPlan(Plan plan) {
        plan.setUpdateTime(LocalDateTime.now());
        boolean update = updateById(plan);
        if (update){
            return SystemResponse.success();
        }
        return SystemResponse.fail("编辑失败");
    }

    /**
     * 获取用户id
     *
     * @return
     */
    private String getUid() {
        return (String) HttpServletRequestUtil.getHttpServletRequest().getAttribute("uid");
    }
}
